#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/5/26  15:55
# @Author: 余浪人
# @email: yulangren520@gmail.com


import requests, base64
from functools import wraps
from apps import setting
from flask import request, jsonify, make_response
from itsdangerous import TimedJSONWebSignatureSerializer
from apps.models.synthesize_model import TL_Connector_Model
from apps.models.system_model import TL_Validation_Model


def generate_token(id, expiration=setting.Config.EXPIRATION):
    s = TimedJSONWebSignatureSerializer(setting.Config.SECRET_KEY, expires_in=expiration)
    return s.dumps({'token': id}).decode('ascii')  # 返回一个token


# 验证接口后台
def apiVerify_token(token_obj):
    @wraps(token_obj)
    def inner(*args, **kwargs):
        accessKey = request.json.get('accessKey','') if request.is_json else request.form.get('accessKey','')
        if not accessKey: accessKey = request.headers.get('Accesskey','') if request.headers.get('Accesskey',None) else request.args.get('accessKey','')
        if not accessKey or len(accessKey) != 32: return jsonify(
            {"status": 1, "msg": base64.b64decode(b'6K+35aGr5YaZdG9rZW7lgLwh55So5LqO5p2D6ZmQ6aqM6K+B').decode()})
        conn = TL_Connector_Model.query.filter(TL_Connector_Model.impower_code == accessKey).first()
        if conn is None: return jsonify({'status': 2, "msg": base64.b64decode(b'5p2D6ZmQ6aqM6K+B5aSx6LSlLHRva2Vu5YC85peg5pWIIQ==').decode()})
        if conn.status == 0: return jsonify({'status': 3, "msg": base64.b64decode(b'5o6l5Y+j5pyq5byA5ZCvLOivt+WFiOW8gOWQr+S9v+eUqCE=').decode()})
        res = token_obj(*args, **kwargs)
        return res

    return inner


# 系统鉴权
def Verify_authorization(obj):
    @wraps(obj)
    def inner(*args, **kwargs):
        domain = request.host_url
        v = TL_Validation_Model.query.order_by(TL_Validation_Model.id.desc()).filter_by().first()
        content = base64.b64decode(
b'PGRpdiBzdHlsZT0icG9zaXRpb246IGFic29sdXRlO3dpZHRoOiAxMDAlO2hlaWdodDogMTAwJTsiPjxoMiBzdHlsZT0idGV4dC1hbGlnbjogY2VudGVyO21hcmdpbi10b3A6IDIwJTsiPuiuv+mXruWPl+mZkCzor7fojrflj5bns7vnu5/mjojmnYM8L2gyPjxkaXY+').decode()
        response = make_response(content)
        response.headers['Content-Type'] = 'text/html; charset=utf-8'
        if not v: return response
        try:
            _response = requests.post(base64.b64decode(b'aHR0cDovL3d3dy50bGNtcy5uZXQvYXV0aGVudGljYXRpb24=').decode(),
                                      data={'domain': domain, 'auth_code': v.v_code})
            if _response.json()['status'] != 0:
                return response
        except:
            return response
        res = obj(*args, **kwargs)
        return res

    return inner
